<?php

/*
 CI Library Utility. A set of functions to help with retreiving database data.
 Written by: Ciprian Dimofte - 01-18-2010
 Amended: 02-02-2010
 */

class Utility{
    public $CI;
    public $timestamp;
    
    public function __construct(){
        $this->CI =& get_instance();
        $this->timestamp = time();
    }
    
    public function get_file_ip($filecode, $server_url){
    	$public_key = $this->CI->keys->public_key(array("filecode"=>$filecode));
        $output = $this->CI->curl_post->post($server_url."files/get_file_ip", array(
                                                                                         "public_key"=>$public_key, 
                                                                                         "timestamp"=>$this->timestamp, 
                                                                                         "filecode"=>$filecode,
                                                                                         ));
        return $output;                                                                                            
    }
    
    public function is_duplicate_download($filecode, $server_url, $file_ip){
        $one_day_ago = time()-86400;
        $sel_dupe = $this->CI->db->query("
        SELECT ID FROM downloads 
        WHERE download_filecode = ? AND download_ip = ? AND download_date >= ?", 
        array($filecode, $this->CI->input->ip_address(), $one_day_ago));
        
        $res_dupe = $sel_dupe->row();
        if($res_dupe->ID || trim($this->CI->input->ip_address()) == trim($this->CI->user->user_account['last_login_ip']) || trim($this->CI->input->ip_address()) == $file_ip){
            return TRUE;
        }else{
            return FALSE;
        }
    }
    
    public function remove_invalid_sessions(){
        //Remove invalid sessions
        $query = "DELETE FROM ci_sessions WHERE user_agent = '0'";
        $this->CI->db->query($query);
    }
    
    public function remove_old_orders(){
        //Remove invalid orders
        $now = time();
        $one_hour_ago = $now - 3600;
        $query = "DELETE FROM tmp_orders WHERE (order_status = '0' AND date <= '" . $one_hour_ago . "') OR user_id = '0'";
        $this->CI->db->query($query);
    }
    
    public function file_info($filecode, $user_id = FALSE, $thumb_size = 250, $thumb_quality = 50){
        
        if($user_id){
            $user_id_check = " AND f.user_id = '".$user_id."'";
        }
        $file_res = $this->CI->db->query("SELECT s.server_url, f.file_password, f.file_name, f.file_size, f.file_description, f.file_type, f.file_date, f.file_code, f.file_ip, f.file_metadata FROM files AS f LEFT JOIN storage_servers AS s ON f.server_id = s.id WHERE f.file_code =  " . $this->CI->db->escape($filecode) . $user_id_check );
        $file_row = $file_res->row();
        
        $filecode_arr = explode(".", $file_row->file_code);
        $file_extension = $filecode_arr[1];
        
        $filetype_arr = explode("/", $file_row->file_type);
        $part_type = $filetype_arr[0];
        
        if($part_type == "image"){
        	$this->CI->load->library("keys");
        	$public_key = $this->CI->keys->public_key(array("filecode"=>$file_row->file_code, "speed"=>1500));
        	$src = $file_row->server_url . "files/download/timestamp/" . $this->CI->keys->timestamp ."/public_key/".$public_key."/speed/1500/filecode/" . $file_row->file_code;
        }else{
        	$src = FALSE;
        }
        
        $out = array(
                        "server_url"=>$file_row->server_url,
                        "file_name"=>$file_row->file_name,
                        "file_password"=>$file_row->file_password,
                        "file_size"=>$file_row->file_size,
                        "file_description"=>$file_row->file_description,
                        "file_type"=>$file_row->file_type,
                        "file_date"=>$file_row->file_date,
                        "file_code"=>$file_row->file_code,
                        "file_extension"=>trim($file_extension),
                        "file_part_type"=>trim($part_type),
                        "file_ip"=>trim($file_row->file_ip),
                        "file_metadata"=>trim($file_row->file_metadata),
                        "thumb_src"=>trim($src)
                        );
        
                        
                        
        return $out;
    }
    
    public function format_size($size = 0){
        $this->CI =& get_instance();
        
        $p0 = pow(1024,1);
        $p1 = pow(1024,2);
        $p2 = pow(1024,3);
        if($size >= $p1 && $size < $p2){
            return number_format(round($size/1024/1024,2),2 , "." , ",")." Mb";
        }
        if($size >= $p0 && $size < $p1){
            return number_format(round($size/1024,1),1 , "." , ",")." Kb";
        }
        if($size >= $p2){
            return number_format(round($size/1024/1024/1024,2),2 , "." , ",")." Gb";
        }
        if($size < $p0){
            return number_format(round($size),0 , "." , ",")." bytes";
        }
    }
    
    public function get_account_types(){
    	
    	$at_query = "
    	           SELECT 
    	               at.ID,
    	               at.account_name,
    	               at.download_speed,
    	               at.max_download_file_size,
    	               at.max_upload_file_size,
    	               at.no_downloads_files_lifetime,
    	               at.remote_uploads,
    	               at.advertising_present,
    	               at.upload_queue_size,
    	               at.simultaneous_uploads_number,
    	               at.account_type_description,
    	               at.image_file_code
    	           FROM
    	               account_types AS at
    	           WHERE
    	               at.ID != -1
    	            ";
    	$sel_at = $this->CI->db->query($at_query);
    	$res_at = $sel_at->result();
    	
    	foreach($res_at as $res){
    		
    		$app_query = "
    		             SELECT
    		                 app.ID,
    		                 app.rate_cost,
    		                 app.rate_time
    		             FROM account_payment_plans AS app
    		             WHERE
    		                 app.account_type_id = ?
    		             ";
    		$sel_app_query = $this->CI->db->query($app_query, array($res->ID));
    		$res_app_query = $sel_app_query->result();
    		
    		$account[$res->account_name] = array();
    		
    		//Make something that will give the signed url to the image corresponding to the file associated for this request
    		//echo $res->image_file_code . "<br />";
            $image_finfo = $this->file_info($res->image_file_code);
            //print_r($image_finfo);
            
            
    		$account[$res->account_name]["plans"] = $res_app_query;
    		$account[$res->account_name]["limits"] = $res;
    		$account[$res->account_name]["image"] = $image_finfo["thumb_src"];
    	}
    	
    	return $account;
    	
    }
    
    //NOTE: we have -1 ADMIN, 0 GUEST(NOMAD), 1 BASIC FREE MEMBER(OGRE)
    //Those above should NEVER change.
    public function get_account_type_id_by_plan_id($plan_id){
    	if($plan_id != -1){
    		$acct_query = "SELECT
	                           at.ID
	                       FROM account_types AS at
	                       LEFT JOIN account_payment_plans AS app
	                           ON at.ID = app.account_type_id
	                       WHERE
	                           app.ID = ? 
	                      ";
	        $sel_acct_id = $this->CI->db->query($acct_query, array($plan_id));
	        $res_acct_id = $sel_acct_id->row();
            return $res_acct_id->ID;
    	}else{
    		//This is NOT hard-coded. This is the default free member account that should never be removed and it's ID should always stay 1
    		return 1;
    	}
    }
    
    public function get_account_type_by_plan_id($plan_id){
        if($plan_id != -1){
            $acct_query = "SELECT
                               at.ID,
                               at.account_name,
                               app.ID AS app_id,
                               app.rate_cost,
                               app.rate_time 
                           FROM account_types AS at
                           LEFT JOIN account_payment_plans AS app
                               ON at.ID = app.account_type_id
                           WHERE
                               app.ID = ? 
                          ";
            $sel_acct_id = $this->CI->db->query($acct_query, array($plan_id));
            $res_acct_id = $sel_acct_id->row();
            return $res_acct_id;
        }else{
        	$acct_query = "SELECT
                               at.ID,
                               at.account_name
                           FROM account_types AS at
                           WHERE
                               at.ID = '1' 
                          ";
            $sel_acct_id = $this->CI->db->query($acct_query, array($plan_id));
            $res_acct_id = $sel_acct_id->row();
            $res_acct_id->rate_cost =  0;
            $res_acct_id->rate_time = -1;
            return $res_acct_id;
        }
    }
    
    
    public function validate_ref(){
    	$sel_ref_ip = $this->CI->db->query("
    	SELECT user_registration_ip
    	FROM users
    	WHERE ID = ? 
    	", array($this->CI->session->userdata("ref_by")));
    	$res_ref_ip = $sel_ref_ip->row();
    	$his_ip = $user_registration_ip;
    	$my_ip = $this->CI->input->ip_address();
    	if($his_ip == $my_ip){
    	   return FALSE;
    	}else{
    		return TRUE;
    	}
    }
    
    public function get_payout_rates_for_user_id($user_id){
        $sel_payout = $this->CI->db->query("
        SELECT 
	        pr.perc_payout,
	        pr.thousand_stream_amount 
        FROM payout_rates AS pr 
        LEFT JOIN account_types AS at 
            ON pr.account_type_id = at.ID 
        LEFT JOIN users AS u
            ON at.ID = u.user_account_type_id 
        WHERE u.ID = ?
        ", array($user_id));
        
        $res_payout = $sel_payout->row();
        return $res_payout;
    }
    
    public function get_payout_rates(){
        $sel_payout = $this->CI->db->query("
        SELECT 
            pr.perc_payout,
            pr.thousand_stream_amount,
            at.account_name 
        FROM payout_rates AS pr 
        LEFT JOIN account_types AS at 
            ON pr.account_type_id = at.ID 
        ");
        
        $res_payout = $sel_payout->result();
        return $res_payout;
    }

    public function get_ref_by($user_id){
        $sel_ref = $this->CI->db->query("SELECT user_ref_by FROM users WHERE ID = ?", array($user_id));
        $res_ref = $sel_ref->row();
        return $res_ref->user_ref_by;
    }
    
    public function get_user_id_by_filecode($filecode){
    	$sel_owner = $this->CI->db->query("SELECT user_id FROM files WHERE file_code = ?", array($filecode));
    	$res_owner = $sel_owner->row();
    	return $res_owner->user_id;
    }
    
}
?>